package com.simulation;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;

import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
public class CollectTask {
	private static int memory, cpu, bandwidth;
	private static int old_memory, old_cpu, old_bandwidth;
	private final static float totalBandwidth = 1000;//总带宽，单位Mbps，根据实际情况设定
	private static Runtime r = Runtime.getRuntime();
	private static String cmd1 = "top -i -b -n 1";
	private static String cmd2 = "cat /proc/net/dev";
	private static BufferedReader br;

	@Scheduled(fixedDelay = 4000)
    public void fixedTask() throws Exception {
    	Process p = null;
    	//使用top命令获取cpu和内存使用信息
    	try {
    		p = r.exec(cmd1);
    		br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    		String line;
    		String[] temp;
    		int free = 0, buffers = 0, cached = 0;

    		while ((line = br.readLine()) != null) {

    			line = line.trim();
    			if (line.startsWith("%Cpu")) {
    				temp = line.split("\\s+");//temp[7]是空闲cpu百分比，例如92.5%
    				float idleCpu = Float.parseFloat(temp[7]);//最后一位是%，要移除
    				cpu = (int)idleCpu;
    				continue;
    			}

    			if (line.startsWith("KiB Mem")) {
    				temp = line.split("\\s+");
    				//物理空闲内存 = 实际空闲内存 + 缓冲 + 缓存
    				free = Integer.parseInt(temp[5]) / 1000;//原始单位是KB，要转换成MB
    				buffers = Integer.parseInt(temp[9]) / 1000;
    				continue;
    			}

    			if (line.startsWith("KiB Swap")) {
    				temp = line.split("\\s+");
    				cached = Integer.parseInt(temp[8]) / 1000;
    				memory = free + buffers + cached;
    				break;
    			}
    		}

    	} catch (Exception e) {
    		e.printStackTrace();
    	} finally {
    		if (br != null) br.close();
    		if (p != null) p.destroy();
    	}

    	//使用proc文件获取网络带宽使用情况
    	try {
            
            //第一次
            long startTime = System.currentTimeMillis();
            p = r.exec(cmd2);
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            String[] temp;
            long in1 = 0, out1 = 0;

            while ((line=br.readLine()) != null) {
                line = line.trim();
                if(line.startsWith("enp2s0")){  
                    temp = line.split("\\s+");
                    in1 = Long.parseLong(temp[1]);//原单位为Byte
                    out1 = Long.parseLong(temp[9]);//原单位为Byte
                    break;
                }
            }
            br.close();
            p.destroy();

            //间隔1秒
            try {  
                Thread.sleep(1000); 
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //第
            long endTime = System.currentTimeMillis();
            p = r.exec(cmd2);
            br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            long in2 = 0, out2 = 0;

            while ((line=br.readLine()) != null) {
                line = line.trim();
                if(line.startsWith("enp2s0")){
                    temp = line.split("\\s+");
                    in2 = Long.parseLong(temp[1]);//原单位为Byte
                    out2 = Long.parseLong(temp[9]);//原单位为Byte
                    break;
                }
            }
            br.close();
            p.destroy();

            if(in1 != 0 && out1 !=0 && in2 != 0 && out2 !=0){
                float interval = ((float)(endTime - startTime)) / 1000;
                float rate = (float)(in2 - in1 + out2 - out1)*8 / 1000000 / interval;
                bandwidth = (int)(totalBandwidth - rate);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


        //对比上一次反馈时的数据，如果偏离较大则开始一次新的反馈
        float dCpu = ((float)Math.abs(cpu - old_cpu)) / old_cpu;
        float dMemory = ((float)Math.abs(memory - old_memory)) / old_memory;
        float dBandwidth = ((float)Math.abs(bandwidth - old_bandwidth)) / old_bandwidth;

        //if (dCpu>0.2 || dMemory>0.2 || dBandwidth>0.2) {

        	String url = "http://localhost/collect?cpu=" + cpu + "&memory=" + memory + "&bandwidth=" + bandwidth;
			//System.out.println(url);
        	//ClientHttpRequest request =new SimpleClientHttpRequestFactory().createRequest(new URI(url), HttpMethod.GET);
			//request.execute();

        	old_cpu = cpu;
        	old_memory = memory;
        	old_bandwidth = bandwidth;
        //}
    }
}
